<?php
/**
 * 处理控制器
 */
namespace app\manage\controller\apply;

use app\manage\controller\Base;
use app\common\model\Member;

/*
use app\common\query\MemberApply;
use app\common\query\MemberCoinBankApply;
use app\common\query\MemberCoin;
use app\common\query\MemberCoinRecord;
*/
class Handle extends Base
{
    private $params;

    public function __construct(){
        parent::__construct();
        if(false==Base::checkToken()){
            $this->error('token error!');
        }
        $params = $this->request->post();
        unset($params['token']);
        $this->params = $params;
    }

    /**
     * 充值审核
     * @return [type] [description]
     */
    public function deal_charge(){
        $params = $this->params;
        $id = $params['id'];
        $status = $params['status']==1?1:2;

        $model = model('operate_charge');

        if(is_array($id)){
            foreach($id as $v):
                $applyData = $model->find($v);
                if(!$applyData){
                    // 记录不存在
                    continue;
                }
                if($applyData['status']!=0){
                    // 已经处理过
                    continue;
                }
                // 锁记录
                $model->where(['id'=>$v])->update(['status'=>4]);

                if($status==1){
                    // 通过处理
                    $result = $this->passOneCharge($applyData);
                    if(false===$result){
                        // 处理失败
                        $model->where(['id'=>$v])->update(['status'=>3,'remark'=>$this->error,'deal_time'=>time()]);
                    }
                    if(true===$result){
                        $model->where(['id'=>$v])->update(['status'=>$status,'deal_time'=>time()]);
                    }
                }else{
                    $model->where(['id'=>$v])->update(['status'=>$status,'deal_time'=>time()]);
                }
            endforeach;
        }else{
            $applyData = $model->find($id);
            if(!$applyData){
                $this->error('记录不存在');
            }
            if($applyData['status']!=0){
                // 已经处理过
                $this->error('该申请已经处理过');
            }
            // 锁记录
            $model->where(['id'=>$id])->update(['status'=>4]);

            if($status==1){
                // 通过处理
                $result = $this->passOneCharge($applyData);
                if(true===$result){
                    $model->where(['id'=>$v])->update(['status'=>$status,'deal_time'=>time()]);
                    }
                if(false===$result){
                    // 处理失败
                    $model->where(['id'=>$id])->update(['status'=>3,'remark'=>$this->error,'deal_time'=>time()]);
                    $this->error($this->error);
                }
            }else{
                $model->where(['id'=>$v])->update(['status'=>$status,'deal_time'=>time()]);
            }
        }
        $this->success('处理完成');
    }
    /**
     * 通过充值申请
     * @param  [type] $data [description]
     * @return [type]            [description]
     */
    private function passOneCharge($data){

        $coinId = $data['coin_id'];
        $amount = $data['amount'];
        $operateId = $data['id'];
        $uid = $data['uid'];

        $chargeModel = model('operate_charge');
        $memberCoinModel = model('member_coin');

        // 计算税后增加的货币数量
        // 获取配置，判断充值货币类型
        $configData = model('coin_config')::coinConfigByType('charge');
        // 充值货币类型是否存在于设置中
        if(!in_array($coinId,array_column($configData, 'coin_id'))){
            $this->error=$config['coin_name'].'不允许充值';
            return false;
        }
        // 获取当前货币提现配置
        $config = array_combine(array_column($configData,'coin_id'), $configData)[$coinId];
        
        // 充值金额计算
        $final_amount = $amount*$config['config']/100;

        $memberCoinModel->startTrans();
        try{
            // 充值增加货币
            $where = ['uid'=>$uid,'coin_id'=>$coinId];
            $beforeAmount = $memberCoinModel->where($where)->value('amount');
            $memberCoinModel -> where($where)->setInc('amount',$final_amount);
            $afterAmount = $memberCoinModel->where($where)->value('amount');
            
            // 资金变动记录
            $record = [
                'operate_id' => $operateId,
                'uid' => $uid,
                'coin_id' => $config['coin_id'],
                'amount' => $final_amount,
                'operate' => 'charge',
                'before_amount' => $beforeAmount,
                'after_amount' => $afterAmount,
                'remark' => '充值'.$amount.'【'.$config['coin_name'].'】（税后'.$final_amount.'）',
                'flag' => 'inc'
            ];
            $memberCoinRecordModel = model('member_coin_record');
            $memberCoinRecordModel -> save($record);

            $memberCoinModel->commit();
        }catch(\Exception $e){
            $memberCoinModel->rollback();
            $this->error=$e->getMessage();
            return false;
        }
        return true;
    }

    /**
     * 处理提现申请
     * @return [type] [description]
     */
    public function deal_withdraw(){
        $params = $this->params;
        $id = $params['id'];
        $status = $params['status']==1?1:2;

        $model = model('operate_withdraw');
        if(is_array($id)){
            //批量处理
            foreach($id as $v):
                $applyData = $model->find($v);
                if(!$applyData){
                    // 记录不存在
                    continue;
                }
                if($applyData['status']!=0){
                    // 已经处理过
                    continue;
                }
                // 锁记录
                $model->where(['id'=>$v])->update(['status'=>4]);

                if($status==1){
                    // 通过处理
                    $model->where(['id'=>$v])->update(['status'=>$status,'remark'=>'已通过','deal_time'=>time()]);
                }else{
                    // 拒绝，资金退回
                    $result = $this->refuseOneWithdraw($applyData);
                    if(true===$result){
                        $model->where(['id'=>$v])->update(['status'=>$status,'remark'=>'已驳回','deal_time'=>time()]);
                    }else{
                        // 处理失败
                        $model->where(['id'=>$v])->update(['status'=>3,'remark'=>$this->error,'deal_time'=>time()]);
                    }
                }
            endforeach;

        }else{
            if(!$applyData = $model->find($id)){
                $this->error('所处理的申请记录不存在');
            }
            if($applyData['status']!=0){
                $this->error('操作失败，该记录已经处理过');
            }

            // 锁记录
            $model->where(['id'=>$id])->update(['status'=>4]);

            if($status==1){
                // 通过处理
                $model->where(['id'=>$id])->update(['status'=>$status,'remark'=>'已通过','deal_time'=>time()]);
            }else{
                // 拒绝，资金退回
                $result = $this->refuseOneWithdraw($applyData);
                if(true===$result){
                    $model->where(['id'=>$id])->update(['status'=>$status,'remark'=>'已驳回','deal_time'=>time()]);
                }else{
                    // 处理失败
                    $model->where(['id'=>$id])->update(['status'=>3,'remark'=>$this->error,'deal_time'=>time()]);
                }
            }
        }
        $this->success('操作成功');
        
    }

    /**
     * 拒绝提现，资金退回账户
     * @return [type] [description]
     */
    private function refuseOneWithdraw($applyData){

        $operateId = $applyData['id'];
        $uid = $applyData['uid'];
        $coinId = $applyData['coin_id'];
        $amount = $applyData['amount'];

        $withdrawModel = model('operate_withdraw');
        $memberCoinModel = model('member_coin');

        $memberCoinModel->startTrans();
        try{

            //资金退回
            $where = ['uid'=>$uid,'coin_id'=>$coinId];
            $beforeAmount = $memberCoinModel->where($where)->value('amount');
            $memberCoinQuery->where($where)->setInc('amount',$amount);
            $afterAmount = $memberCoinModel->where($where)->value('amount');
            
            // 资金变动记录
            $record = [
                'operate_id' => $operateId,
                'uid' => $uid,
                'coin_id' => $coinId,
                'amount' => $amount,
                'operate' => 'withdraw_refuse',
                'before_amount' => $beforeAmount,
                'after_amount' => $afterAmount,
                'remark' => '拒绝提现，资金退回',
                'flag' => 'inc'
            ];
            $memberCoinRecordModel = model('member_coin_record');
            $memberCoinRecordModel -> save($record);

            $memberCoinModel->commit();
        }catch(\Exception $e){
            $memberCoinModel->rollback();
            $this->error=$e->getMessage();
            return false;
        }
        return true;
    }

    /**
     * 代理申请处理
     * @return [type] [description]
     */
    public function deal_member_apply(){
        $params = $this->params;

        $id = $params['id'];
        $status = $params['status'];
        $p_agent = strtoupper($params['p_agent']);

        $memberApplyQuery = new \app\common\query\MemberApply;
        $memberModel = new Member;

        // 通过申请
        if($status==1){
            $applyData = $memberApplyQuery->getOneData(['id'=>$id]);
            if(!$applyData){
                $this->error('操作失败，申请记录不存在');
            }
            $member = $memberModel->where(['mid'=>$applyData['mid']])->find();
            if(!$member){
                $this->error('操作失败，该用户不存在');
            }
            if($member['is_agent']){
                $this->error('操作失败，该用户已经是报单中心');
            }
            // 判断父级报单中心是否存在
            if(!$memberModel->where(['mid'=>$p_agent,'is_agent'=>1])->find()){
                $this->error('操作失败，设置的父级报单中心不存在！');
            }else{
                $memberModel->where(['mid'=>$applyData['mid']])->update(['is_agent'=>1,'p_agent'=>$p_agent,'agent_type_id'=>1]);
            }
            $memberApplyQuery -> saveOneData(['status'=>$status],['id'=>$id]);
        }else{
            if(is_array($id)){
                $memberApplyModel = new \app\common\model\MemberApply;
                $memberApplyModel -> where(['id'=>$id]) -> update(['status'=>$status]);
            }else{
                $memberApplyQuery -> saveOneData(['status'=>$status],['id'=>$id]);
            }
        }

        
        
        $this->success('处理完成');
    }

}